package com.iot.manage.controller;

import com.alibaba.fastjson.JSONObject;
import com.iot.manage.pojo.Device;
import com.iot.manage.pojo.SysCode;
import com.iot.manage.result.Code;
import com.iot.manage.result.Result;
import com.iot.manage.service.DeviceService;
import com.iot.manage.service.TokenService;
import com.iot.manage.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

/**
 * 设备管理控制层
 *
 * @author zhuzhi
 */
@RestController
@RequestMapping("/api/private/v1")
public class DeviceIotController {

    @Autowired
    private TokenService tokenService;

    @Autowired
    private DeviceService deviceService;

    /**
     * 查询设备信息列表
     *
     * @param token
     * @param query 模糊查询关键字
     * @param pagenum 当前页
     * @param pagesize 每页条数
     * @return
     */
    @GetMapping("/findDevicesList")
    public Result findDevicesList(
            @RequestHeader("token") String token,
            @RequestParam("query") String query,
            @RequestParam("pagenum") int pagenum,
            @RequestParam("pagesize") int pagesize) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<Device> devicesList;
        int devicesTotal;
        try{
            devicesList = deviceService.findDevicesList(query,pagenum,pagesize);
            devicesTotal = deviceService.countDevicesList(query);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        Map<String, Object> map = new HashMap<>();
        map.put("total",devicesTotal);
        map.put("pagenum",pagenum);
        map.put("devicesList",devicesList);
        return result.build(map, Code.S200);
    }

    /**
     * 查询设备类型下拉框
     *
     * @param token
     * @return
     */
    @GetMapping("/findDtypeCodeList")
    public Result findDtypeCodeList(@RequestHeader("token") String token){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<SysCode> dtypeCodeList;
        try{
            dtypeCodeList = deviceService.findDtypeCodeList();
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(dtypeCodeList, Code.S200);
    }

    /**
     * 查询设备模型下拉框
     *
     * @param token
     * @return
     */
    @GetMapping("/findModelCodeList")
    public Result findModelCodeList(@RequestHeader("token") String token){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<SysCode> modelCodeList;
        try{
            modelCodeList = deviceService.findModelCodeList();
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(modelCodeList, Code.S200);
    }

    /**
     * 查询设备厂家下拉框
     *
     * @param token
     * @return
     */
    @GetMapping("/findCompanyCodeList")
    public Result findCompanyCodeList(@RequestHeader("token") String token){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<SysCode> companyCodeList;
        try{
            companyCodeList = deviceService.findCompanyCodeList();
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(companyCodeList, Code.S200);
    }

    /**
     * 查询设备网关下拉框
     *
     * @param token
     * @return
     */
    @GetMapping("/findGatewayCodeList")
    public Result findGatewayCodeList(@RequestHeader("token") String token){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<SysCode> gatewayCodeList;
        try{
            gatewayCodeList = deviceService.findGatewayCodeList();
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(gatewayCodeList, Code.S200);
    }

    /**
     * 查询设备状态下拉框
     *
     * @param token
     * @return
     */
    @GetMapping("/findDeviceStatusList")
    public Result findDeviceStatusList(@RequestHeader("token") String token){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<SysCode> deviceStatusList;
        try{
            deviceStatusList = deviceService.findDeviceStatusList();
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(deviceStatusList, Code.S200);
    }

    /**
     * 查询父设备下拉框
     *
     * @param token
     * @return
     */
    @GetMapping("/findParentCodeList")
    public Result findParentCodeList(@RequestHeader("token") String token){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        List<SysCode> parentCodeList;
        try{
            parentCodeList = deviceService.findParentCodeList();
            SysCode sysCode = new SysCode();
            sysCode.setCodeValue(" ");
            sysCode.setCodeName("无");
            parentCodeList.add(0,sysCode);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(parentCodeList, Code.S200);
    }

    /**
     * 新增设备信息
     *
     * @param token
     * @param params 设备信息参数
     * @return
     */
    @PostMapping("/addDeviceInfo")
    public Result addDeviceInfo(
            @RequestHeader("token") String token,
            @RequestBody JSONObject params) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            if(null != findDeviceInfoById(token,params.getString("deviceCode")).getData()){
                return result.build(null, Code.D411);
            }
            params.put("deviceId", UUID.randomUUID().toString().replace("-", ""));
            params.put("deviceArg", StringUtils.replaceBlank(params.get("deviceArg").toString()));
            deviceService.addDeviceInfo(params);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }

    /**
     * 根据设备ID或设备标识查询设备信息
     *
     * @param token
     * @param params 设备ID或设备标识
     * @return
     */
    @GetMapping("/findDeviceInfoById/{deviceId}")
    public Result findDeviceInfoById(
            @RequestHeader("token") String token,
            @PathVariable("deviceId") String params){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        Device device;
        try{
            device = deviceService.findDeviceInfoById(params);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(device, Code.S200);
    }

    /**
     * 修改设备信息
     *
     * @param token
     * @param params 设备信息参数
     * @return
     */
    @PutMapping("/updateDeviceInfo/{oldDeviceCode}")
    public Result updateDeviceInfo(
            @RequestHeader("token") String token,
            @PathVariable("oldDeviceCode") String oldDeviceCode,
            @RequestBody JSONObject params){
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            if (!(oldDeviceCode.equals(params.get("deviceCode")))){
                if(null != findDeviceInfoById(token,params.getString("deviceCode")).getData()){
                    return result.build(null, Code.D411);
                }
            }
            params.put("deviceArg", StringUtils.replaceBlank(params.get("deviceArg").toString()));
            deviceService.updateDeviceParentCodeInfo(params);
            deviceService.updateDeviceInfo(params);
        } catch (Exception e){
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }

    /**
     *删除设备信息
     *
     * @param token
     * @param deviceId 设备ID
     * @return
     */
    @DeleteMapping("/removeDeviceInfo/{deviceId}/{deviceCode}")
    public Result removeDeviceInfo(
            @RequestHeader("token") String token,
            @PathVariable("deviceId") String deviceId,
            @PathVariable("deviceCode") String deviceCode) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            int total = deviceService.countDeviceParentByCode(deviceCode);
            if (total > 0){
                return result.build(null,Code.WARM);
            }
            deviceService.removeDeviceInfo(deviceId);
            deviceService.deleteRelevancyAreaById(deviceId);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }

    /**
     *将子设备的父设备置空
     *
     * @param token
     * @param deviceId 设备ID
     * @param deviceCode 设备标识
     * @return
     */
    @DeleteMapping("/removeDeviceInfoParent/{deviceId}/{deviceCode}")
    public Result removeDeviceInfoParent(
            @RequestHeader("token") String token,
            @PathVariable("deviceId") String deviceId,
            @PathVariable("deviceCode") String deviceCode) {
        Result result = new Result();
        if (!tokenService.validate(token)) {
            return result.build(null,Code.D404);
        }
        try {
            deviceService.updateDeviceInfoParent(deviceCode);
            deviceService.removeDeviceInfo(deviceId);
            deviceService.deleteRelevancyAreaById(deviceId);
        } catch (Exception e) {
            e.printStackTrace();
            return result.build(null,Code.D400);
        }
        return result.build(null, Code.S200);
    }
}
